import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import debounce  from 'lodash.debounce';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import AddDeviceGroup from './components/AddDeviceGroup';
import ParentOrgListComponent from '../System/components/ParentOrgListComponent';
import { DeviceGroupListItem } from './data.d';
import { deviceGroupList , addDeviceGroup, updateDeviceGroup, removeDeviceGroup} from './service';

const { Search } = Input;

const EquipmentGroup: React.FC<{}> = () => {
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<DeviceGroupListItem>({});
  const actionRef = useRef<ActionType>();

  //添加设备分组
  const addDeviceGroupCommand = async (values:DeviceGroupListItem) =>{
    if (values != null && values != undefined) {
      new Promise((resolve, reject) => {
        addDeviceGroup(values)
          .then((res) => {
            if(res){
              if (res.code === 200) {
                message.success('添加成功');
                handleUpdateModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
                resolve(true);
              }else if(res.code === 4501){
                message.error('组名已经存在');
                resolve(false);
              }
            }else {
              message.error('修改失败');
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }

  //编辑设备分组
  const updateDeviceGroupCommand = async (values:DeviceGroupListItem) =>{
    if (values != null && values != undefined) {
      new Promise((resolve, reject) => {
        updateDeviceGroup(values)
          .then((res) => {
            if(res){
              if (res.code === 200) {
                message.success('添加成功');
                handleUpdateModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
                resolve(true);
              }else if(res.code === 4501){
                message.error('组名已经存在');
                resolve(false);
              }
            }else {
              message.error('修改失败');
              resolve(false);
            }
          })
          .catch((error) => {
            message.error('请求失败');
            reject(error);
          });
      });
    }
  }

  //设备分组弹出框确定
  const handleUpdate = async (values:DeviceGroupListItem) =>{
    if (values != null && values != undefined) {
      if(values.id){
        updateDeviceGroupCommand(values);
      }else{
        addDeviceGroupCommand(values);
      }
    }
  }

  //分组列表--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此设备分组将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          removeDeviceGroup(id)
            .then((res) => {
              if(res){
                if (res.code === 200) {
                  const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  hide();
                  actionRef.current?.reload?.();
                  resolve(true);
                } else {
                  message.error('删除失败'+res.message);
                  resolve(false);
                }
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };
  const columns: ProColumns<DeviceGroupListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
      width:80,
    },
    {
      title: '分组ID',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true, 
      width:80,
    },
    {
      title: '分组名称',
      dataIndex: 'name',
      width:150,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Search
              placeholder="请输入分组名称"
              onSearch={debounce(value=>{form.submit()}, 500)}
              onChange={debounce(value=>{form.submit()}, 500)}
              style={{ width: 200 }}
            />
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgId',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <ParentOrgListComponent 
              defaultvalue={-1}
              type="orgId"
              selectChange={(value) => {
                form.setFieldsValue({"orgId": value});
                form.submit();
              }}
              >
            </ParentOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'orgName',
      width:150,
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '设备数量',
      dataIndex: 'num',
      width:100,
      valueType: 'text',
      hideInSearch: true, 
      render: (_, record) => <><span>{record.num} 个</span></>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      valueType: 'text',
      hideInSearch: true,
      ellipsis:true,
      width:250,
    },
    {
      title: '操作',
      width:200,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              record.type = "detail";
              setFormValues(record);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              record.type = "edit";
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a 
            onClick={() => {
              delConfirm(record.id);
            }}
          >删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<DeviceGroupListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => {
            handleUpdateModalVisible(true);
            setFormValues({});
          }}>
            <PlusOutlined /> 新建分组
          </Button>,
        ]}
        request={(params, sorter, filter) => deviceGroupList({ ...params, sorter, filter })}
        columns={columns}
      />
      <AddDeviceGroup values={formValues} onSubmit={handleUpdate} onCancel={() => handleUpdateModalVisible(false)} modalVisible={updateModalVisible}></AddDeviceGroup>
    </PageContainer>
  );
};

export default EquipmentGroup;
